package app.fugema.shop.main.order.view;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ProgressBar;

import com.base.common.app.LoginUtils;
import com.base.common.model.bean.ADInfo;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.Base64Utils;
import com.base.common.utils.DialogUtils;
import com.base.common.utils.JavaMethod;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.ada.ImageAddRecyAdapter;
import com.base.common.view.adapter.connector.BaseItemMultiType;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityOrderAfterSaleCreateBinding;
import app.fugema.shop.http.HttpService;
import app.fugema.shop.main.order.model.OrderRefundModelResult;
import app.fugema.shop.main.order.model.RefundApplyParams;
import app.fugema.shop.main.order.vm.OrderAfterSaleVM;

import java.util.ArrayList;
import java.util.List;

import app.fugema.shop.main.setting.model.UploadPicResult;
import io.reactivex.Observable;

public class OrderAfterSaleCreateActivity extends BaseTitleActivity<ActivityOrderAfterSaleCreateBinding, OrderAfterSaleVM>
{
    //申请退款

    public static void start(Context context, String orderId ,String itemId)
    {
        Intent intent = new Intent(context, OrderAfterSaleCreateActivity.class);
        intent.putExtra("orderNumber", orderId);
        intent.putExtra("itemId", itemId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_after_sale_create);
    }

    private OrderRefundModelResult.RefundModeBean modeBean;
    private ImageAddRecyAdapter imageAddRecyAdapter;
    private String buyerMsg;

    private long orderId;
    private String userKey;

    private List<String> refundResaon;
    private RefundApplyParams applyParams = new RefundApplyParams();

    private List<String> netImgList;
    private String itemId = "";

    @Override
    protected boolean keyboardEnable() {
        return true;
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("申请售后",R.color.white);

        netImgList = new ArrayList<>();
            //选择退款原因
            binding.tvRefundReason.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    if( refundResaon == null || refundResaon.size() == 0 )
                    {
                        return;
                    }
                    addFragment(OrderAfterSaleCreateCancelDF.getInstance(refundResaon ,buyerMsg, new OrderAfterSaleCreateCancelDF.OnResultInterface() {
                        @Override
                        public void onSuccess(String sMsg)
                        {
                            buyerMsg = sMsg;

                            binding.tvRefundReason.setText(buyerMsg);
                        }
                    }));
                }
            });

            binding.etEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                    binding.tvTextCount.setText(s.toString().length() + "/200");
                }
            });

            imageAddRecyAdapter = new ImageAddRecyAdapter(this) {
                @Override
                public Observable<Object> getObservable(String path)
                {
                    viewModel.upLoadPIc(Base64Utils.imgFileToBase64Str(path))
                             .observe(OrderAfterSaleCreateActivity.this, new BaseViewObserver<LiveDataWrapper<UploadPicResult>>()
                             {
                                 @Override
                                 protected void onSuccess(LiveDataWrapper<UploadPicResult> data)
                                 {
                                     if( data.data.isSuccess() )
                                     {
                                         LogUtil.e( data.data.getRomoteImage() );
                                         netImgList.add( data.data.getRomoteImage() );
                                     }
                                 }
                             });

                    // 原来 代码里面的 上传图片
                    //viewModel.getUpLoadFilesObservable(path, HttpService.getUpLoadFilesService())
                    return viewModel.getUpLoadFilesObservable(path, HttpService.getUpLoadFilesService());
                }
            };
            imageAddRecyAdapter.setMaxCount(3);
            imageAddRecyAdapter.setVideoCount(0);
            imageAddRecyAdapter.setSelectedGif(false);
            //imageAddRecyAdapter.setAutoUpload(true);
            imageAddRecyAdapter.setAutoUpload(false);
            binding.rvRecyclerViewImages.setAdapter(imageAddRecyAdapter);

            imageAddRecyAdapter.addFoot();
            binding.rtvOK.setOnClickListener(new OnClickCheckedUtil() {
                @Override
                public void onClicked(View view) {
                    uploadAndPostRefund();
                }
            });
    }

    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        userKey = LoginUtils.getToken();
       String orderNumber = intent.getStringExtra("orderNumber");
       if( UIUtils.isNotEmpty( orderNumber ) )
       {
            orderId = Long.parseLong( orderNumber );
       }
       itemId  = intent.getStringExtra("itemId");

        applyParams.setUserkey( userKey );

        viewModel.getOrderRefundModel(orderId,itemId,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<OrderRefundModelResult>>(this)
                 {
                    @Override
                    protected void onSuccess(LiveDataWrapper<OrderRefundModelResult> data)
                    {
                       //拿到 退款 提交订单信息
                       if( data.data.isSuccess() && UIUtils.isNotEmpty( data.data.getRefundMode() ) )
                       {
                           modeBean = data.data.getRefundMode();
                           refundResaon = getReasonsFromResult(modeBean);

                           applyParams.setOrderid( modeBean.getId() );

                           applyParams.setAmount( modeBean.getMaxRefundAmount() );
                           //退货数量
                           applyParams.setReturnquantity(modeBean.getMaxRGDNumber());
                           applyParams.setContactperson( modeBean.getContactPerson() );
                           applyParams.setContactcellPhone( modeBean.getContactCellPhone() );
                           applyParams.setItemId(itemId);
                            /*
                                   refundtype=1&
                                   returnquantity=0&
                                   amount=195.00&
                                   reason=商品破损&
                                   contactperson=梁心颐&
                                   contactcellPhone=13125043081&
                                   refundpaytype=3&
                                   reasondetail=测试提交退款说明&
                                   certpic1=/temp/20210702172626845261.png certpic2 certpic3
                           */

                           binding.setItem(modeBean);
                           binding.executePendingBindings();
                       }
                    }
                 });
        if( UIUtils.isNotEmpty(itemId) )
        {
            binding.tvRefundType.setText("退货退款");
        }
    }

    private void uploadAndPostRefund()
    {
        if (UIUtils.isEmpty(buyerMsg))
        {
            UIUtils.showToastSafesClose("请选择退款原因");
            return;
        }
        netImgList.clear();
        if( UIUtils.isNotEmpty(itemId) )
        {
            //1 仅退款 2：退款退货
            applyParams.setRefundtype( 2 );
        }
        else
        {
            //1 仅退款 2：退款退货
            applyParams.setRefundtype( 1 );
        }


        //退款支付方式 1： 原路返回  3：退到预付款  这里就给个 固定值
        applyParams.setRefundpaytype( 3 );

        applyParams.setReason(buyerMsg);


        String etStr = binding.etEdit.getText().toString();
        if( UIUtils.isNotEmpty( etStr )  )
        {
            applyParams.setReasondetail( etStr );
        }
        // 设置图片
        //certpic1=/temp/20210702172626845261.png certpic2 certpic3

        if (imageAddRecyAdapter != null && imageAddRecyAdapter.getChildCount() > 0)
        {
            //直接上传
            List<ADInfo> list1 = imageAddRecyAdapter.getDataList(BaseItemMultiType.TYPE_CHILD, BaseItemMultiType.TYPE_CHILD_ONE);

            for (ADInfo adInfo : list1)
            {
                String imgPath =  adInfo.getImagePatch();
                LogUtil.e( imgPath );
                viewModel.upLoadPIc( Base64Utils.imgFileToBase64Str(imgPath) )
                         .observe(OrderAfterSaleCreateActivity.this, new BaseViewObserver<LiveDataWrapper<UploadPicResult>>()
                         {
                            @Override
                            protected void onSuccess(LiveDataWrapper<UploadPicResult> data)
                            {
                                if( data.data.isSuccess() )
                                {
                                    LogUtil.e( data.data.getRomoteImage() );
                                    netImgList.add( data.data.getRomoteImage() );
                                    if( netImgList.size() ==  list1.size())
                                    {
                                        postApplyRefund();
                                    }
                                }
                            }
                         });
            }
        }
        else
        {
            postApplyRefund();
        }
    }

    private void postApplyRefund()
    {
        if (modeBean != null)
        {
            for( int i=0;i < netImgList.size();i++ )
            {
                if(i == 0)
                {
                    applyParams.setCertpic1(netImgList.get(0));
                }
                if(i == 1)
                {
                    applyParams.setCertpic2(netImgList.get(1));
                }
                if(i == 2)
                {
                    applyParams.setCertpic3(netImgList.get(2));
                }
            }

            //binding.etEdit.getText().toString(), pic
            viewModel.applyOrderRefund(applyParams )
                     .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(this) {
                        @Override
                        protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                        {
                            //{"success":true, "msg":"提交成功","id":30}
                            //{"success":false,"msg":"该订单条目已删除或不属于该用户"}
                            if( data.data.isSuccess() )
                            {
                                LiveEventBus.get(AppConstants.EventKey.ORDER_AFTER_SALE, String.class).post(""+orderId);
                                UIUtils.showToastSafes("提交成功");
                                finish();
                            }
                            else
                            {
                                UIUtils.showToastSafesClose( data.data.getMsg() );
                            }
                        }
                    });
        }
    }

    private List<String> getReasonsFromResult(OrderRefundModelResult.RefundModeBean resultModel)
    {
        List<String>  mResaons = new ArrayList<>();
        if(UIUtils.isNotEmpty( resultModel.getRefundReasons() ))
        {
            for (OrderRefundModelResult.RefundReasonsBean tempReason : resultModel.getRefundReasons())
            {
                mResaons.add(tempReason.getAfterSalesText());
            }
        }
        return mResaons;
    }

    private void uopladFileImgByYangKuo()
    {

        //0  全部成功   1正在上传  2 上传完毕但是有图片上传失败
        int err = imageAddRecyAdapter.checkedUpload();
        if (err == 0) {
            List<ADInfo> list1 = imageAddRecyAdapter.getDataList(BaseItemMultiType.TYPE_CHILD, BaseItemMultiType.TYPE_CHILD_ONE);
            String pic = "";
            if (!UIUtils.isEmpty(list1)) {
                pic = list1.get(0).getImageUrl();
                for (int i = 1; i < list1.size(); i++) {
                    pic += "," + list1.get(i).getImageUrl();
                }
            }
            //save(buyerMsg, pic);
        } else {

            if (err == 1)
            {
                Dialog progressDialog = DialogUtils.progressDialog(getActivity());
                ProgressBar pbProgress = progressDialog.getWindow().findViewById(R.id.pbProgress);
                ProgressBar pbProgressSum = progressDialog.getWindow().findViewById(R.id.pbProgressSum);

                UIUtils.showToastSafes("正在上传图片，请稍后");

                imageAddRecyAdapter.setUploadImageCallBack(new ImageAddRecyAdapter.UploadImageCallBack() {
                    @Override
                    public void onProgressSum(String percentSum) {
                        LogUtil.d(percentSum + "%  percentSum");
                        if (pbProgressSum != null) {
                            pbProgressSum.setProgress(JavaMethod.getInt(percentSum));
                        }
                    }

                    @Override
                    public void onProgress(String percent) {
                        LogUtil.d(percent + "%    percent");
                        if (pbProgress != null) {
                            pbProgress.setProgress(JavaMethod.getInt(percent));
                        }
                    }

                    @Override
                    public void onComplete(boolean success) {
                        dismissLoad();
                        if (success) {
                            //save();
                        } else {
//                            LogUtil.d("上传完毕,但有图片上传失败");
                            DialogUtils.showSimpleDialog(getActivity(), false, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //save();
                                    dialog.dismiss();
                                }
                            }, "上传完毕,但有图片上传失败\n是否继续提交？");

                        }
                    }
                });

            } else {

                DialogUtils.showSimpleDialog(getActivity(), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //save();
                        dialog.dismiss();
                    }
                }, "上传完毕,但有图片上传失败\n是否继续提交？");

            }

        }
    }

}
